// OGoMojo
// Whitemice.MOGI.MOGIMon
// License: LGPL
// Copyright: Whitemice Consulting, 2006
// Author(s): Adam Tauno Williams (awilliam@whitemice.org)
using System;
using System.Net;
using log4net;
using System.Threading;
using System.Collections;
using Whitemice.MOGI;
using Whitemice.MOGI.RPC2;

namespace Whitemice.MOGI.MOGIMon
{
	public class MOGIMon
	{
		protected IServer			server;
		protected int				delay;
		protected Auditor			auditor;
		protected RecordKeeper		keeper;
		protected Worker			worker;
	
		public static void Main()
		{
			MOGIMon daemon;
			
			daemon = new MOGIMon();
			daemon.Run();
		}
		
		public MOGIMon()
		{
			server = new Whitemice.MOGI.RPC2.Server("MOGIMon");
			server.Hostname = server.GetDirectiveValue("MOGIMon", "Hostname");			
			server.Credentials = new NetworkCredential(
				server.GetDirectiveValue("MOGIMon", "Username"),
				server.GetDirectiveValue("MOGIMon", "Secret"));
			if (!server.Connected)
			{
				server.Log.Fatal("Unable to connect to back office.");
				Thread.CurrentThread.Abort();
			}	
			Log.Debug("Connected to back office.");
			keeper = new RecordKeeper(server);
			keeper.Connect();
			auditor = new Auditor(server, keeper);
			auditor.Connect();
			worker = new Worker(server, keeper);
			worker.Load();
			delay = Convert.ToInt32(server.GetDirectiveValue("MOGIMon", "LoopDelay"));
			server.Log.Debug("Loop interval is " + delay.ToString());
		}
				
		public void Run()
		{
			Hashtable 	changes;

			while ( true )
			{
				server.Log.Debug("Scanning for changes.");
				changes = auditor.Changes;
				server.Log.Debug("Running workers.");
				foreach(string documentName in changes.Keys)
					worker.Do((Change)changes[documentName]);
				server.Log.Debug("Sleeping.");
				Thread.Sleep(delay);
			}
		}
		
		public ILog Log
		{
			get { return server.Log; }
		}
	}
}
